package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.constant.SystemCode;
import com.example.demo.domain.AjaxResult;
import com.example.demo.utils.InterfaceUtil;
import com.ideabank.po.SOFInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/testSOF")
public class TestSOFController {
    /**
     * 设置签名算法
     *
     * @param signmethod
     * @return
     */
    @RequestMapping("/setSignMethod")
    @ResponseBody
    public AjaxResult setSignMethod(String signmethod) {
        AjaxResult ar = new AjaxResult();
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if ("SGD_SM3_SM2".equals(signmethod)) {
            svc.SOF_setSignMethod(SystemCode.SGD_SM3_SM2);
        } else {
            svc.SOF_setSignMethod(SystemCode.SGD_SHA1_RSA);
        }
        ar.setSuccess(true);
        return ar;
    }

    /**
     * 获取服务器证书
     *
     * @return
     * @throws Exception
     */
        @RequestMapping("/getCert")
    @ResponseBody
    public AjaxResult getCert() throws Exception {
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        String cert = svc.SOF_getServerCertificate();
        return StringUtils.isNotBlank(cert) ? AjaxResult.SUCCESS(cert) : AjaxResult.ERROR("文件签名失败");
    }

    /**
     * 数字签名
     *
     * @param inData
     * @return
     * @throws Exception
     */
    @RequestMapping("/signData")
    @ResponseBody
    public AjaxResult signData(String inData) throws Exception {
        log.info("<=== signData inData:{} ===>", inData);
        byte[] inDataByte = inData.getBytes("GBK");
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        String signdata = svc.SOF_signData(inDataByte);
        return StringUtils.isNotBlank(signdata) ? AjaxResult.SUCCESS(signdata) : AjaxResult.ERROR("数字签名失败");
    }

    /**
     * 数字验签
     *
     * @param data
     * @return
     * @throws Exception
     */
    @RequestMapping("/verifySignedData")
    @ResponseBody
    public AjaxResult verifySignedData(@RequestBody String data) throws Exception {
        log.info("<=== verifySignedData data:{} ===>", data);
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        Map<String, String> map = JSONObject.parseObject(data, Map.class);
        byte[] inDataByte = map.get("inData").getBytes("GBK");
        boolean status = svc.SOF_verifySignedData(map.get("cert"), inDataByte, map.get("signValue"));
        return status ? AjaxResult.SUCCESS() : AjaxResult.ERROR("数字验签失败");
    }

    /**
     * 消息签名
     *
     * @param inData
     * @return
     * @throws Exception
     */
    @RequestMapping("/signMessage")
    @ResponseBody
    public AjaxResult signMessage(String inData) throws UnsupportedEncodingException {
        byte[] inDataByte = inData.getBytes("GBK");
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        String signdata = svc.SOF_SignMessage(inDataByte);
        return StringUtils.isNotBlank(signdata) ? AjaxResult.SUCCESS(signdata) : AjaxResult.ERROR("消息签名失败");
    }

    /**
     * 消息验签
     *
     * @param signValue
     * @return
     * @throws Exception
     */

    @RequestMapping("/verifySignMessage")
    @ResponseBody
    public AjaxResult verifySignMessage(String signValue) throws UnsupportedEncodingException {
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        boolean status = svc.SOF_verifySignedMessage(signValue);
        return status ? AjaxResult.SUCCESS() : AjaxResult.ERROR("数字验签失败");
    }

    /**
     * 不带原文消息签名
     *
     * @param inData
     * @return
     * @throws Exception
     */
    @RequestMapping("/signMessageDetach")
    @ResponseBody
    public AjaxResult signMessageDetach(String inData) throws UnsupportedEncodingException {
        byte[] inDataByte = inData.getBytes("GBK");
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        String signdata = svc.SOF_SignMessage(inDataByte);
        return StringUtils.isNotBlank(signdata) ? AjaxResult.SUCCESS(signdata) : AjaxResult.ERROR("消息签名失败");
    }

    /**
     * 不带原文消息验签
     *
     * @param
     * @return
     * @throws Exception
     */

    @RequestMapping("/verifySignMessageDetach")
    @ResponseBody
    public AjaxResult verifySignMessageDetach(String inData, String signValue) throws Exception {
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        byte[] inDataByte = inData.getBytes("GBK");
        boolean status = svc.SOF_verifySignedMessageDetach(inDataByte, signValue);
        return status ? AjaxResult.SUCCESS() : AjaxResult.ERROR("数字验签失败");
    }


    /**
     * 文件签名
     *
     * @param inData
     * @return
     * @throws Exception
     */
    @RequestMapping("/signFile")
    @ResponseBody
    public AjaxResult signFile(String inData) throws Exception {
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        String signdata = svc.SOF_signFile(inData);
        return StringUtils.isNotBlank(signdata) ? AjaxResult.SUCCESS(signdata) : AjaxResult.ERROR("文件签名失败");
    }


    /**
     * 文件验签
     *
     * @param data
     * @return
     * @throws Exception
     */

    @RequestMapping("/verifySignFile")
    @ResponseBody
    public AjaxResult verifySignFile(@RequestBody String data) throws Exception {

        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        Map<String, String> map = JSONObject.parseObject(data, Map.class);
        boolean status = svc.SOF_verfySignedFile(map.get("cert"), map.get("inData"), map.get("signValue"));
        return status ? AjaxResult.SUCCESS() : AjaxResult.ERROR("文件验签失败");
    }


    /**
     * 验证证书
     *
     * @param cert
     * @return
     */
    @RequestMapping("/validateCert")
    @ResponseBody
    public AjaxResult validateCert(String cert) {
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        long status = svc.SOF_validateCert(cert);
        return status == 1 ? AjaxResult.SUCCESS() : AjaxResult.ERROR("验证证书失败");
    }

    /**
     * 解析证书
     *
     * @param cert
     * @param type
     * @return
     */
    @RequestMapping("/getCertInfo")
    @ResponseBody
    public AjaxResult getCertInfo(String cert, String type) {
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        String result = svc.SOF_getCertInfo(cert, Integer.parseInt(type.substring(2, type.length()), 16));
        return StringUtils.isNotBlank(result) ? AjaxResult.SUCCESS(result) : AjaxResult.ERROR("解析证书失败或者该项为空！");
    }

    /**
     * 获取随机数
     *
     * @param randomLength
     * @return
     */
    @RequestMapping("/getRandom")
    @ResponseBody
    public AjaxResult getRandom(String randomLength) {
        log.info("<=== getRandom randomLength:{} ===>", randomLength);
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        String result = svc.SOF_genRandom(Short.parseShort(randomLength));
        return StringUtils.isNotBlank(result) ? AjaxResult.SUCCESS(result) : AjaxResult.ERROR("获取随机数失败");
    }

    /**
     * 设置加密算法
     *
     * @param method
     * @return
     */
    @RequestMapping("/setEncryptMethod")
    @ResponseBody
    public AjaxResult setEncryptMethod(String method) {
        log.info("<=== setEncryptMethod method:{} ===>", method);
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        if ("SGD_SM4_ECB".equals(method)) {
            svc.SOF_setEncryptMethod(SystemCode.SGD_SM4_ECB);
        } else {
            svc.SOF_setEncryptMethod(SystemCode.SGD_SM4_CBC);
        }
        return AjaxResult.SUCCESS();
    }

    /**
     * 获取指定证书
     *
     * @param status
     * @return
     */
    @RequestMapping("/getServerCertificateByUsage")
    @ResponseBody
    public AjaxResult getServerCertificateByUsage(String status) {
        log.info("<=== getServerCertificateByUsage status:{} ===>", status);
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        /** status:1加密，2是签名 */
        String cert = svc.SOF_getServerCertificateByUsage(Short.parseShort(status));
        log.info("<=== getServerCertificateByUsage cert:{} ===>", cert);
        return StringUtils.isNotBlank(cert) ? AjaxResult.SUCCESS(cert) : AjaxResult.ERROR("获取指定证书失败");
    }

    /**
     * 加密数据
     *
     * @param inData
     * @param cert
     * @return
     * @throws Exception
     */
    @RequestMapping("/encryptData")
    @ResponseBody
    public AjaxResult encryptData(String inData, String cert) throws Exception {
        log.info("<=== encryptData inData:{}, cert:{} ===>", inData, cert);
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        byte[] inDataByte = inData.getBytes("GBK");
        String encryptData = svc.SOF_encryptData(cert, inDataByte);
        log.info("<=== encryptData encryptData:{} ===>", encryptData);
        return StringUtils.isNotBlank(cert) ? AjaxResult.SUCCESS(encryptData) : AjaxResult.ERROR("加密失败");
    }

    /**
     * 解密数据
     *
     * @param inData
     * @return
     * @throws Exception
     */
    @RequestMapping("/decryptData")
    @ResponseBody
    public AjaxResult decryptData(String inData) throws Exception {
        log.info("<=== decryptData inData:{} ===>", inData);
        SOFInterface svc = InterfaceUtil.getAppInstance();
        if (svc == null) {
            return AjaxResult.ERROR("初始化失败");
        }
        byte[] result = svc.SOF_decryptData("1", inData);
        log.info("<=== decryptData result:{} ===>", result);
        return result != null && result.length > 0 ? AjaxResult.SUCCESS() : AjaxResult.ERROR("解密失败");
    }


}
